//
//  ProjectListViewController.swift
//  GiteeClient
//
//  Created by 王志标 on 2020/10/14.
//

import UIKit
import MJRefresh
import AwaitKit
import PKHUD
import UITableView_FDTemplateLayoutCell
import SnapKit

/// 控制器类型
enum ProjectType {
    case FEATURED
    case POPULAR
    case LASTUPDATE
    case PROJECT_OWNER
    case PROJECT_OHTER
    case STARED_PRO
    case WATCH_PRO
}



/// 展示项目列表控制器 首页 搜索等页可用
class ProjectListViewController: BaseViewController {

    // 列表
    var projectListTableView:UITableView!
    var cellID = "projectitemcellid"
    // 默认是推荐类型
    var type:ProjectType = .FEATURED
    // 数据源
    lazy var projectArray:ProjectArrayModel = ProjectArrayModel()
    
    var currentPage = 1
    
    var userModel:UserModel?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    init(type: ProjectType,user:UserModel? = nil) {
        super.init(nibName: nil, bundle: nil)
        self.type = type
        self.userModel = user
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        projectListTableView.frame = view.bounds
    }
    
}

// MARK: - 设置界面
extension ProjectListViewController {
    
    func setupUI() {
        
        projectListTableView = UITableView()
        projectListTableView.register(UINib.init(nibName: "ProjectItemTableViewCell", bundle: nil), forCellReuseIdentifier: cellID)
        let value = UIView.AutoresizingMask.flexibleHeight.rawValue | UIView.AutoresizingMask.flexibleWidth.rawValue
        projectListTableView.autoresizingMask = UIView.AutoresizingMask.init(rawValue: value)
        projectListTableView.delegate = self
        projectListTableView.dataSource = self
        projectListTableView.separatorStyle = .none
        view.addSubview(projectListTableView)
        
        projectListTableView.snp.makeConstraints { (make) in
            make.top.left.right.bottom.equalToSuperview()
        }
        
        let mjH = MJRefreshNormalHeader {
            self.currentPage = 1
            self.loadData(page: self.currentPage)
        }
        mjH?.lastUpdatedTimeLabel.isHidden = true
        projectListTableView.mj_header = mjH
        mjH?.beginRefreshing()
        
        let mjF = MJRefreshBackNormalFooter {
            self.currentPage += 1
            self.loadData(page: self.currentPage)
        }
        projectListTableView.mj_footer = mjF
        
        
        projectListTableView.emptyDataSetDelegate = self
        projectListTableView.emptyDataSetSource = self
        
        if #available(iOS 13.0, *) {
            projectListTableView.backgroundColor = Colors.backgroundColor
        }
    }
}

// MARK: - 加载数据
extension ProjectListViewController {
    
    // 下拉刷新加载数据
    func loadData(page: Int){
        
        var url = ""
        switch type {
        
        case .FEATURED://推荐
            url = URLs.FEATURED_URL
        case .POPULAR:// 热门
            url = URLs.POPULAR_URL
        case .LASTUPDATE:// 最近更新
            url = URLs.LAST_URL
            
        case .WATCH_PRO:// 本人watch
            if self.userModel == nil {
                resetData()
                return
            }
            url = URLs.V3URL + "user/" + self.userModel!.id.description + "/watched_projects"
        case .STARED_PRO://本人satar
            if self.userModel == nil {
                resetData()
                return
            }
            url = URLs.V3URL + "user/" + self.userModel!.id.description + "/stared_projects"
        case .PROJECT_OHTER://他人项目
            if self.userModel == nil {
                resetData()
                return
            }
            url = URLs.V3URL + "user/" + self.userModel!.id.description + "/projects"
            
        case .PROJECT_OWNER://本人项目
            if self.userModel == nil {
                resetData()
                return
            }
            url = URLs.V3URL + "projects"
     
        }
        
        url += "?page=\(page)"
        
        // 异步加载
        DispatchQueue.global().async {
        
            let result:Result<[ProjectMdoel?]> = NetWorkTool.shared.getArrayRequest(url: url, parameters: nil)
            
            DispatchQueue.main.async {
                if result.code == 0 {
                    if page == 1 {
                        self.projectArray.items = result.data as? [ProjectMdoel]
                    }else {
                        self.projectArray.items?.append(contentsOf: (result.data as? [ProjectMdoel])!)
                        if result.data?.count == 0 {
                            self.projectListTableView.mj_footer.endRefreshingWithNoMoreData()
                            return
                        }
                    }
                    self.projectListTableView.reloadData()
                }else {
                    HUD.flash(.label(result.message), delay: 2.0)
                }
                self.projectListTableView.mj_header.endRefreshing()
                self.projectListTableView.mj_footer.endRefreshing()
            }
        }
    }
    
    func resetData(){
        self.projectArray.items = [ProjectMdoel]()
        self.projectListTableView.reloadData()
        self.projectListTableView.mj_header.endRefreshing()
        self.projectListTableView.mj_footer.endRefreshing()
        
    }
    
}

// MARK: - tableview的代理和数据源方法
extension ProjectListViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return projectArray.items?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! ProjectItemTableViewCell
      
        cell.selectionStyle = .none
        cell.model = projectArray.items![indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return tableView.fd_heightForCell(withIdentifier: cellID) { (cell) in
            
            (cell as! ProjectItemTableViewCell).selectionStyle = .none
            (cell as! ProjectItemTableViewCell).model = self.projectArray.items![indexPath.row]
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let project = projectArray.items![indexPath.row]
        let detialVC = ProjectDetialViewController(project: project)
        detialVC.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(detialVC, animated: true)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.listViewDidScrollCallback?(scrollView)
    }
}

extension ProjectListViewController: JXPagingViewListViewDelegate {
    public func listView() -> UIView {
        return self.view
    }
    
    public func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> ()) {
        self.listViewDidScrollCallback = callback
    }

    public func listScrollView() -> UIScrollView {
        return self.projectListTableView
    }
}
